/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.util;

import org.hibernate.dialect.lock.OptimisticEntityLockException;
import org.springframework.dao.OptimisticLockingFailureException;

public class ExceptionUtil {

  private static final int MAX_NESTED_EXCEPTIONS = 100;

  private static boolean isExceptionOfClass(Throwable t, Class clzz) {
    for (int i = 0; i < MAX_NESTED_EXCEPTIONS; i++) {
      if (t == null) {
        return false;
      } else if (clzz.isInstance(t)) {
        return true;
      } else {
        t = t.getCause();
      }
    }
    throw new RuntimeException("Exception with " + MAX_NESTED_EXCEPTIONS + " nested causes: ", t);
  }

  public static boolean isOptimisticLockExcetpion(Exception e) {
    return isExceptionOfClass(e, OptimisticEntityLockException.class)
        || isExceptionOfClass(e, OptimisticLockingFailureException.class);
  }

  public static void main(String[] args) {
    Exception exception = new RuntimeException();
    System.out.println(isOptimisticLockExcetpion(new Exception(exception)));
  }
}
